package com.icss.mqsp.servlet;

import com.icss.mqsp.builder.IBuilder;
import com.icss.mqsp.builder.factory.BuilderFactory;
import com.icss.mqsp.commitLog.CommitLog;
import com.icss.mqsp.util.RequestCondition;
import com.icss.pangu.logging.Log;
import com.icss.pangu.logging.LogFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MainServlet extends HttpServlet {
	private Log log = LogFactory.getLog(MainServlet.class);
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RequestCondition rc = new RequestCondition(request);
		String reqName = request.getParameter("pid");
		String op = (String) rc.getCondition("op");
		 String uuid = request.getParameter("uuid");
		 String divid = request.getParameter("divid");
		 CommitLog commitLog = new CommitLog();
		 String key = request.getParameter("key");
		 if(key!=null&&"saveLog".equals(key)) {
			 boolean flag = commitLog.saveLog(uuid, divid, request);
			 
			 PrintWriter pw = null;
			 
			 try {
				 pw = response.getWriter();
				 response.setContentType("application/json;charset=UTF-8");
				 pw.print("{'saveLog':"+flag+"}");
				
				pw.flush();
			} catch (IOException e) {
				this.log.error(e.toString());
			} finally {
				pw.close();
			}
		 }else {
			 this.log.info("op=" + op);
				IBuilder builder = BuilderFactory.getBuilder(op);
				JSONObject rs = builder.exec(rc);
				JSONArray array = new JSONArray();
				if ("INDEX".equals(reqName)) {
					List list = new ArrayList();
					list.add(rs.getJSONObject("0"));
					list.add(rs.getJSONObject("1"));
					list.add(rs.getJSONObject("2"));
					list.add(rs.getJSONObject("3"));
					response.setContentType("application/json;charset=UTF-8");
					response.getWriter().print(list);
				} else if ("CWZB_QG".equals(reqName)) {
					response.setContentType("application/json;charset=UTF-8");
					response.getWriter().print(rs.getJSONObject("0"));
				} else {
					this.log.info("rs=" + rs);
					if ("cacheReport".equals(op)) {
						print(rs, response);
					} else {
						print(rs, response);
					}
				}
		 }
		
	}

	private void print(JSONObject rs, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			pw.print(rs);
			pw.flush();
		} catch (IOException e) {
			this.log.error(e.toString());
		} finally {
			pw.close();
		}
	}
}
